// pages/recommendedcopy/recommendedcopy.js
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    goodsPhotoUrls:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    console.log('options', options)
    getApp().request({
      url: getApp().api.default.marketing,
      data: {
        goods_id: options.good_id,
      },
      success: function (t) {
        console.log('tttt', t)
        if (t.code === 0) {
          that.setData({
            list: t.data
          })
        }else if(t.code === 1){
          wx.showToast({
            title: '该商品未设置推品文案',
            icon: 'none',
            duration: 2000
          })

        }
      }
    })
  },


  xiazai: function (e) {
    var content = e.currentTarget.dataset.content
    var pic_list =  e.currentTarget.dataset.pic_list
    wx.setClipboardData({
      data: content,
      success: function (res) {
        that.setData({
          goodsPhotoUrls:pic_list
        })
        that.share(content)
      }
    });
  },
  share: function (content) {
    var that = this;
    var data = content;
    wx.showLoading({
      title: '图片下载中..',
    })
    var all_n = data.length;
    that.dow_temp(0);
  },

  //下载单个内容

  dow_temp: function (i, callback) {
    var that = this;
    var data = that.data.goodsPhotoUrls;
    var all_n = data.length;
    if (i < all_n) {
      wx.authorize({
        scope: 'scope.writePhotosAlbum',
        success() {
          // 用户已经同意小程序使用相册的授权
          console.log(' data[i]', data,'i+++++',i)
          const downloadTask = wx.downloadFile({
            url: data[i],
            success: function (res) {
              var temp = res.tempFilePath;
              console.info("临时路径", temp)
              wx.saveImageToPhotosAlbum({
                filePath: temp,
                success: function () {
                  console.info('第', (i + 1), '张保存成功');
                  that.dow_temp(i + 1);
                  //开启分享浮层
                  if (i == all_n - 1) {
                    console.log('全部保存完成++')
                    wx.showToast({
                      icon: 'none',
                      title: '下载成功',
                    })
                  }
                },
                fail: function () {
                  console.info('第', (i + 1), '张保存失败');
                  that.dow_temp(i);
                }
              })
            },
            fail: function (res) {
              wx.showToast({
                icon: 'none',
                title: '获取图片临时路径失败',
              })
            }
          })
        },
        fail: function () {
          wx.showToast({
            icon: 'none',
            title: '获取授权失败',
          })
        }
      })
    }
  },

})